package com.dyz.wsw.common.utils.security;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * AES加解密
 * @author dyz
 * Time 2024/6/26 21:00
 */
public class AES {
    /**
     * 根据AES密钥进行密文解密
     * @param encryptedText 原始密文
     * @param secretKey AES密钥
     * @return 原始明文
     * @throws Exception 解密时出现的各种异常
     */
    public static String decrypt(String encryptedText, String secretKey) throws Exception{
        // 确保密钥长度至少为16个字符
        byte[] keyBytes = secretKey.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec key = new SecretKeySpec(keyBytes, "AES");

        // AES的块大小是128位（16字节），所以只需要前16个字符作为IV
        byte[] ivBytes = secretKey.substring(0, 16).getBytes(StandardCharsets.UTF_8);
        IvParameterSpec iv = new IvParameterSpec(ivBytes);

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // 注意PKCS5Padding是PKCS7Padding的Java实现
        cipher.init(Cipher.DECRYPT_MODE, key, iv);

        byte[] decodedValue = Base64.getDecoder().decode(encryptedText);
        byte[] decryptedValue = cipher.doFinal(decodedValue);

        return new String(decryptedValue, StandardCharsets.UTF_8);
    }
}
